<?php
class Authentication_model extends CI_Model 
{

	public function __construct()
	{
		$this->load->database();
	}
	
	public function authenticate ($username, $password)
	{
		$sql = "select * from user " .
			   "where username = ? " .
			   "and password = ?";
		
		$query = $this->db->query($sql, array($username, md5($password))); 

		if($query->num_rows == 1)
		{
			return true;
		}
	}	
	
	public function is_user ($username)
	{
		return $this->has_role ($username, 'ROLE_USER');
	}
	
	public function is_admin ($username)
	{
		return $this->has_role ($username, 'ROLE_ADMIN');
	}
	
	private function has_role ($username, $role)
	{
		$sql = "select * from user u, role r, user_role ur " .
			   "where u.username = ? " .
			   "and u.id = ur.user_id " .
			   "and r.id = ur.role_id " .
			   "and r.authority = ?";
		
		$query = $this->db->query($sql, array($username, $role)); 

		if($query->num_rows == 1)
		{
			return true;
		}
	}
	
}
?>
